package com.mlm.mlmapp.activity;

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.mlm.mlmapp.BuildConfig;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.adapter.DownloadProgressDialog;
import com.mlm.mlmapp.adapter.view.adapter.MainAdapter;
import com.mlm.mlmapp.adapter.view.listener.DialogListener;
import com.mlm.mlmapp.adapter.view.listener.OnBannerClickedListener;
import com.mlm.mlmapp.adapter.view.listener.OnGridItemSelectedListener;
import com.mlm.mlmapp.adapter.view.listener.OnSyClickedListener;
import com.mlm.mlmapp.adapter.view.listener.VersionCheckDialog;
import com.mlm.mlmapp.cons.Constants;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity implements
        OnGridItemSelectedListener {
    private AQuery aq;
    private MainAdapter adapter;
    private RecyclerView recyclerView;
    private List<JSONObject> array=new ArrayList<>();
    boolean applyNewVersionflag = false;
    private DownloadManager dowanloadmanager = null;
    private DownloadChangeObserver downloadObserver;
    private long lastDownloadId = 0;
    @Pref
    Prefs_ pref;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/");
    ProgressDialog pd;

    @AfterViews
    public void init() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float width=dm.widthPixels*dm.density;
        float height=dm.heightPixels*dm.density;
       Log.d("sort","First method:"+dm.toString()+"\n"+"Second method:"+"Y="+height+";X="+width);

        // btn_home.setBackgro  undColor(getResources().getColor(R.color.red));
        btn_home.setCompoundDrawablesWithIntrinsicBounds(null, getResources()
                .getDrawable(R.drawable.homechecked), null, null);
        btn_home.setTextColor(getResources().getColor(R.color.red));
        setTranStatusBar();
        aq = new AQuery(this);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        final GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.isPositionHeader(position) ? layoutManager
                        .getSpanCount() : 1;
            }
        });
        recyclerView.setLayoutManager(layoutManager);
        // recyclerView.addItemDecoration(new GridMarginDecoration(this, 1, 1,
        // 1, 1));
        recyclerView.setHasFixedSize(true);
        adapter = new MainAdapter(MainActivity.this, array,
                MainActivity.this,
                new OnBannerClickedListener() {

                    @Override
                    public void onItemClick(View v, String url) {
                        // TODO Auto-generated method stub
                        if (url != null && !"".equals(url))

                            ShowWebView_
                                    .intent(MainActivity.this)
                                    .extra("url", url).extra("title","详情").start();
                    }
                }, new OnSyClickedListener() {

            @Override
            public void onSyItemClick(View v, String id) {
                // TODO Auto-generated method stub
                HairDresserDetailActivity_
                        .intent(MainActivity.this)
                        .extra("id", id).start();
            }
        });
        recyclerView.setAdapter(adapter);
        getShareInfo();
        aq.progress(new AQProgressDialog(this)).ajax(HTTPCons.get_styles_action, JSONArray.class,
                new AjaxCallback<JSONArray>() {

                    @Override
                    public void callback(String url, JSONArray object,
                                         AjaxStatus status) {
                        // TODO Auto-generated method stub
                        Log.d("sort","MainActivity:callback: "+object);
                        super.callback(url, object, status);
                        if (status.getCode() == -101) {
                            Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                                    Toast.LENGTH_SHORT);
                            return;
                        }
                       for(int i=0;i<object.length();i++){
                           try {
                               array.add(object.getJSONObject(i));
                           } catch (JSONException e) {
                               e.printStackTrace();
                           }
                       }
                        adapter.notifyDataSetChanged();

                    }

                });
        aq.ajax(HTTPCons.get_new_version, JSONObject.class,
                new AjaxCallback<JSONObject>() {

                    @Override
                    public void callback(final String url, JSONObject object,
                                         AjaxStatus status) {
                        // TODO Auto-generated method stub
                        super.callback(url, object, status);
                        if (object != null) {
                            PackageManager pm = MainActivity.this.getPackageManager();
                            PackageInfo pi = null;
                            try {
                                pi = pm.getPackageInfo(MainActivity.this.getPackageName(), 0);
                            } catch (PackageManager.NameNotFoundException e) {
                                e.printStackTrace();
                            }
                            int currVersionCode = pi.versionCode;
                            final int versionCode = getJsonInt(object, "versionCode");
                            if (currVersionCode >= versionCode) {
                                return;
                            }
                            String versionName = getJsonString(object, "versionName");
                            String des = getJsonString(object, "versionDescription");
                            final String downurl = getJsonString(object, "download");
                            final VersionCheckDialog dialog = new VersionCheckDialog(MainActivity.this, new DialogListener() {
                                @Override
                                public void onApply(JSONObject obj, String clazz) {
                                    applyNewVersionflag = true;
                                    download(downurl, versionCode);
                                    MainActivity.this.finish();
                                }

                                @Override
                                public void onCancel() {
                                    MainActivity.this.finish();
                                }
                            }, des, versionName);
                            dialog.show();
                            dialog.setCanceledOnTouchOutside(false);

                        }
                    }

                });


    }

    class DownloadChangeObserver extends ContentObserver {


        public DownloadChangeObserver(Handler handler) {
            super(handler);
            // TODO Auto-generated constructor stub
        }


        @Override
        public void onChange(boolean selfChange) {
            updateProgress(queryDownloadStatus());
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (downloadObserver != null)
            getContentResolver().unregisterContentObserver(downloadObserver);
    }

    private void download(String downurl, int versioncode) {
//        dpd=new DownloadProgressDialog(this);
//        dpd.show();


        String serviceString = Context.DOWNLOAD_SERVICE;
        dowanloadmanager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        Uri uri = Uri.parse(downurl);
        Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS).mkdir();
        String filename = "美啦美" + BuildConfig.BUILD_TYPE+"V"+versioncode + ".apk";
        String path = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + filename;
        File tempFile = new File(path);
        Uri tempUri = Uri.fromFile(tempFile);
        pref.edit().downloadUri().put(tempUri.toString()).apply();
        if (tempFile.exists()) {
            if(queryDownloadStatus()>0&&queryDownloadStatus()<=100){
                Toast.makeText(this, "美啦美正在下载最新版本，请稍候", Toast.LENGTH_SHORT).show();
                return;
            }
            CommonUtils.openFile(this, tempUri);
            return;
        }else{
            Toast.makeText(this, "美啦美正在下载最新版本，请稍候", Toast.LENGTH_SHORT).show();
        }
        lastDownloadId = dowanloadmanager.enqueue(new DownloadManager.Request(uri)
                .setAllowedNetworkTypes(
                        DownloadManager.Request.NETWORK_MOBILE
                                | DownloadManager.Request.NETWORK_WIFI)
                .setAllowedOverRoaming(false)
                .setDescription("美啦美正在下载最新版本，请稍候")
                .setTitle("美啦美更新")
              .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
                .setMimeType("application/vnd.android.package-archive")
                .setDestinationInExternalPublicDir(
                        Environment.DIRECTORY_DOWNLOADS, filename));
        pref.edit().downloadID().put(lastDownloadId + "").apply();
        downloadObserver = new DownloadChangeObserver(null);
        getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);

    }

    DownloadProgressDialog dpd;

    public void updateProgress(int progress) {
        //  dpd.setIntProgress(progress);
    }
    int currProgress = 0;
    private int queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();

        query.setFilterById(Long.valueOf(pref.downloadID().get()));
        Cursor c = null;

        try {
            c = dowanloadmanager.query(query);

            if (c != null && c.moveToFirst()) {
                int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));

                int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);
                int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
                int fileSizeIdx =
                        c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                int bytesDLIdx =
                        c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                String title = c.getString(titleIdx);
                int fileSize = c.getInt(fileSizeIdx);
                int bytesDL = c.getInt(bytesDLIdx);

                // Translate the pause reason to friendly text.
                int reason = c.getInt(reasonIdx);
                StringBuilder sb = new StringBuilder();
                sb.append(title).append("\n");
                sb.append("Downloaded ").append(bytesDL).append(" / ").append(fileSize);
                currProgress = bytesDL * 100 / fileSize;
                // Display the status
                switch (status) {
                    case DownloadManager.STATUS_PAUSED:
                    case DownloadManager.STATUS_PENDING:
                    case DownloadManager.STATUS_RUNNING:
                        //正在下载，不做任何
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                updateProgress(currProgress);
                            }
                        });
                        break;
                    case DownloadManager.STATUS_SUCCESSFUL:
                        //完成
//                        downloadFinish(null);
//                        Log.v("sort", "下载完成");
//                  dowanloadmanager.remove(lastDownloadId);
                        break;
                    case DownloadManager.STATUS_FAILED:
                        //清除已下载的内容，重新下载
                        dowanloadmanager.remove(lastDownloadId);
                        break;
                }
            }
        } catch (Exception e) {
            Log.e("sort", "queryDownloadStatus: " + e.getMessage());
        } finally {
            c.close();
        }
        return currProgress;
    }

    public Handler handler = new Handler();

    @Override
    public void onGridItemClick(View v, int position) {
        // Toast.makeText(MainActivity.this, "Grid item clicked position is " +
        // position, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onItemAppointment(View v, int position) {
        // TODO Auto-generated method stub

        if (position > 0) {
            try {
                JSONObject obj = array.get(position - 1);
                BookActivity_.intent(this)
                        .extra("id", obj.getString("stylistId")).extra("styleid", obj.getString("id")).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onItemCollection(View v, int position) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onHairDresserClick(View v, int position) {
        if (position > 0) {
            try {
                JSONObject obj = array.get(position - 1);
                HairDresserDetailActivity_.intent(this)
                        .extra("id", obj.getString("stylistId")).start();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onHairStyleClick(View v, int position) {
        // TODO Auto-generated method stub
        if (position > 0) {
            try {
                JSONObject obj = array.get(position - 1);
                String linkType=getJsonString(obj,"linkType");
                if ("2".equals(CommonUtils.getJsonString(obj, "linkType"))) {
                    HairStylePublicDetailActivity_.intent(this)
                            .extra("id", obj.getString("id")).start();
                }else{
                    HairStyleDetailActivity_.intent(this)
                            .extra("id", obj.getString("id")).start();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // HairStyleActivity_.intent(this).extra("id",position);
    }

    public void getShareInfo() {
        aq.progress(new AQProgressDialog(MainActivity.this)).ajax(get_share_info + "?type=1&linkId=1", JSONObject.class,
                new AjaxCallback<JSONObject>() {

                    @Override
                    public void callback(String url, JSONObject obj,
                                         AjaxStatus status) {
                        // TODO Auto-generated method stub
                        if (status.getCode() == -101) {
//                            Toast.makeText(ShowWebView.this, "网络异常,请检查网络", Toast.LENGTH_SHORT);
                            return;
                        }
                        if (status.getCode() != 200) {
//                            Toast.makeText(ShowWebView.this, "网络异常:" + status.getCode(), Toast.LENGTH_SHORT).show();
                        } else {
                            JSONObject object = obj;
                        }
                        JSONObject object = obj;
                        Constants.SHARE_PROXINFO = getJsonString(object, "proxInfo");
                        Constants.SHARE_PROXTITLE = getJsonString(object, "proxTitle");
                        Constants.SHARE_STYINFO = getJsonString(object, "styInfo");
                        Constants.SHARE_STYTITLE = getJsonString(object, "styTitle");
                        Constants.SHARE_OPUSINFO = getJsonString(object, "opusInfo");
                        Constants.SHARE_OPUSTITLE = getJsonString(object, "opusTitle");

//                        "opusTitle" -> "来自美啦美的发型"
//                        "styInfo" -> "这位美啦美的发型设计师真的超赞！在线预约不办卡就有VIP折扣呢！"
//                        "proxTitle" -> "美啦美时尚平台"
//                        "proxInfo" -> " 一份来自美丽的邀请函"
//                        "opusInfo" -> "感觉这款发型适合我，快来帮我瞅瞅~直接通过美啦美预约有活动呢！"
//                        "styTitle" -> "来自美啦美的设计师"
                    }
                });


    }

    @ViewById
    Button btn_home;

    @Click
    void btn_home() {
        // MainActivity_.intent(this).start();

    }

    @Click
    void btn_dresser() {
        HairDresserListActivity_.intent(this).extra("bookflag", false).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Click
    void btn_appointment() {
        BookActivity_.intent(this).start();
    }

    @Click
    void btn_style() {
        HairStyleListActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Click
    void btn_userinfo() {
        UserInfoActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }
    @Receiver(actions = CollectionsActivity.COLLECTION_REFRESH, registerAt = Receiver.RegisterAt.OnCreateOnDestroy)
    protected void onOrderRefresh(Intent intent) {
        if (intent.getStringExtra("refreshflag") != null && "0".equals(intent.getStringExtra("refreshflag"))) {
            aq.progress(new AQProgressDialog(this)).ajax(HTTPCons.get_styles_action, JSONArray.class,
                    new AjaxCallback<JSONArray>() {

                        @Override
                        public void callback(String url, JSONArray object,
                                             AjaxStatus status) {
                            // TODO Auto-generated method stub

                            super.callback(url, object, status);
                            if (status.getCode() == -101) {
                                Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                                        Toast.LENGTH_SHORT);
                                return;
                            }
                            array.clear();
                            for(int i=0;i<object.length();i++){
                                try {
                                    array.add(object.getJSONObject(i));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }

                    });
        }
    }
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finishApplication();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
